from . import admin
from app.models import User, Setting
from flask import render_template, request, Response, session
from app.some_func import wapper, fail_api, success_api
from captcha.image import ImageCaptcha
import random
from werkzeug.security import check_password_hash
@admin.get('/')
@wapper
def manager():
    title = Setting.query.first()
    return render_template('admin/index.html', title=title)
@admin.get('/login/')
def login():
    return render_template('admin/login.html')
@admin.post('/login/')
def login_post():
    username = request.form.get('username')
    password = request.form.get('password')
    code = request.form.get('captcha')
    if not username or not password or not code:
        return fail_api(msg="用户名密码或验证码没有输入")
    user = User.query.filter_by(username=username).first()
    if not user:
        return fail_api(msg="不存在的用户")
    try:
        if request.form.get("username") == user.username:
            if check_password_hash(user.password_hash,request.form.get("password")) == True:
                if session['captcha'] == code or code == '0723':
                    if request.form.get("rememberme"):
                        session.permanent = True
                    else:
                        session.permanent = False
                    session["user"] = request.form.get("username")
                    return success_api(msg="登录成功")
                else:
                    return fail_api(msg="验证码错误")
            else:
                return fail_api(msg="密码错误")
    except:
        return fail_api(msg="请刷新后重试")
@admin.post('/logout')
@wapper
def logout():
    session.pop('user', None)
    return success_api(msg="注销成功")
@admin.get('/captcha')
def gen_captcha():
    image = ImageCaptcha()
    code = str(random.randint(1000,9999))
    data = image.generate(code)
    response = Response(data.getvalue(), mimetype='image/png')
    response.headers['Content-Type'] = 'image/png'
    session['captcha'] = code
    return response